package cn.net.sinodata.system.msghandler.parse.entitymapping;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JsonEntityMapping extends BaseEntityMapping {

//    @Override
//    String getValueByPath(Object result, String source) {
//        JSONObject jsonResult =  (JSONObject)result;
//        Object value = jsonResult.getByPath(source);
//        if (value == null) {
//            return null;
//        } else {
//            return value.toString();
//        }
//    }

    // 如果表达式过于复杂的话，可以使用json-path这个jar包。
    @Override
    String getValueByPath(Object result, String source) {
        ObjectNode jsonResult =  (ObjectNode)result;
        if (source.contains("[") && source.contains("]")) {
            JsonNode atNode = jsonResult.at(convertToXPath(source));
            return atNode.asText();
        }

        String[] partSources = source.split("\\.");
        JsonNode currentNode = jsonResult;
        for (String partSource : partSources) {
            if (!source.contains("[") && !source.contains("]")) {
                // 取的是数组
                int i = partSource.indexOf("[");
                String name = partSource.substring(0, i);
                String indexStr = partSource.substring(i+1, partSource.length()-1);
                Integer index = Integer.valueOf(indexStr);
                currentNode = currentNode.path(name);
                if (currentNode.isArray()) {
                    currentNode = currentNode.path(index);
                } else {
                    return null;
                }
            } else {
                // 普通节点
                currentNode = currentNode.path(partSource);
            }
        }
        return currentNode.asText();
    }

    private static String convertToXPath(String source) {
        String xpath = source.replace('.', '/');
        xpath = "/" + xpath;
        return xpath;
    }

}
